package com.iyunwen.datatool.datastorage.impl;

import com.iyunwen.datatool.common.annotations.EventTypeAnnotation;
import com.iyunwen.datatool.common.enums.DataSourceTypeEnum;
import com.iyunwen.datatool.dao.EventDataMapper;
import com.iyunwen.datatool.datastorage.DataStorage;
import com.iyunwen.datatool.model.dbdo.EventDataDO;
import com.iyunwen.datatool.model.vo.BaseNormalizationDataVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @description: 数据db操作
 * @author: Zhu.Guodong
 * @create: 2020-03-20 15:26
 * @version:
 */
@Slf4j
@Component
@EventTypeAnnotation(eventType = DataSourceTypeEnum.EVENT_LOG)
public class EventLogDataStorageImpl implements DataStorage<EventDataDO> {
    @Autowired
    EventDataMapper eventDataMapper;

    @Override
    public void createTable(String tableName) {
        try {
            eventDataMapper.createTable(tableName);
        } catch (Exception e) {
            throw new RuntimeException("创建表失败");
        }
    }

    @Override
    public void insertAllDataToDatabase(List<EventDataDO> eventData, String tableName) {
        if (null != eventData && eventData.size() > 0){
            int pointsDataLimit = 10000;//限制条数
            Integer size = eventData.size();
            //判断是否有必要分批
            if (pointsDataLimit < size) {
                int part = size / pointsDataLimit;//分批数
                log.info("共有:" + size + "条，！" + " 分为:" + part + "批");
                for (int i = 0; i < part; i++) {
                    //1000条
                    List<EventDataDO> tempDataList = eventData.subList(0, pointsDataLimit);
                    try {
                        eventDataMapper.insertBatch(tempDataList, tableName);
                    } catch (Exception e) {
                        throw new RuntimeException("数据存储失败", e);
                    }
                    //剔除
                    eventData.subList(0, pointsDataLimit).clear();
                }
                if (!eventData.isEmpty()) {
                    try {
                        eventDataMapper.insertBatch(eventData, tableName);
                    } catch (Exception e) {
                        throw new RuntimeException("数据存储失败", e);
                    }
                }
            } else {
                try {
                    eventDataMapper.insertBatch(eventData, tableName);
                } catch (Exception e) {
                    throw new RuntimeException("数据存储失败", e);
                }
            }
        }
    }
}
